<template>
  <div>
    <!-- 面包屑 -->
    <div class="bread-crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>资产类目</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="main-middle">
      <el-card class="box-card">
        <!-- 查询条件 -->
        <el-row class="table-selbox" v-if="btnSel">
          <el-form :inline="true" :model="formInline">
            <el-form-item label="分类名称">
              <el-autocomplete
                v-model="formInline.cateName"
                :fetch-suggestions="querySearchAsync"
                placeholder="请输入内容"
                @select="handleSelect"
                clearable
              ></el-autocomplete>
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-search" @click="selHandle">搜索</el-button>
            </el-form-item>
          </el-form>
        </el-row>
        <!-- 基本操作按钮-->
        <el-row class="table-btns" v-if="[btnAdd,btnDel,btnUpload,btnDown].indexOf(true) > -1">
          <el-button
            v-if="btnAdd"
            type="success"
            size="medium"
            icon="el-icon-document-add"
            @click="addHandle"
          >添加</el-button>
          <el-button
            type="danger"
            size="medium"
            icon="el-icon-delete"
            @click="batchRemove"
            v-if="btnDel"
          >删除</el-button>
        </el-row>
        <!-- 数据列表 -->
        <el-table
          :data="assetsTypeData"
          border
          @selection-change="selsChange"
          width="100%"
          height="580"
          ref="assetsTypeData"
        >
          <el-table-column type="selection" width="40"></el-table-column>
          <el-table-column prop="compName" label="所属公司" width="150"></el-table-column>
          <el-table-column label="归属类目" width="150">
            <template slot-scope="scope">
              {{ scope.row.parentId | getName(parentList) }}
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" prop="cateCode" label="分类编号" width="150"></el-table-column>
          <el-table-column :show-overflow-tooltip="true" prop="cateName" label="分类名称"></el-table-column>
          <el-table-column
              label="管理"
              align="center"
              width="160"
              v-if="[btnDel,btnEdit].indexOf(true) > -1"
            >
            <template slot-scope="scope">
              <el-button type="danger" size="mini" @click="handleDelete(scope.row)" v-if="btnDel">删除</el-button>
              <el-button size="mini" @click="editHandle(scope.row)" v-if="btnEdit">修改</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="table-pageblock">
          <!-- current-page 当前页数  page-size 每页显示数 total 总页数-->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[20,50,80,100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </el-card>
      <!-- 弹窗 新增or修改 -->
      <el-dialog
        :title="textMap[dialogStatus]"
        :visible.sync="dialogFormVisible"
        :close-on-click-modal="false"
      >
        <el-form ref="editForm" :model="editForm" label-width="80px" :rules="editFormRules">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="所属公司" prop="compId">
                <el-select v-model="editForm.compId" auto-complete="off" placeholder="请选择"  style="width:100%;">
                  <el-option label="无" value=""></el-option>
                  <el-option
                    v-for="(item,index) in compList"
                    :key="index"
                    :label="item.compName"
                    :value="item.compId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属类目" prop="parentId">
                <el-select v-model="editForm.parentId" auto-complete="off" placeholder="请选择"  style="width:100%;">
                  <el-option label="无" value="0"></el-option>
                  <el-option
                    v-for="(item,index) in parentList"
                    :key="index"
                    :label="item.cateName"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="分类编号" prop="cateCode">
                <el-input v-model="editForm.cateCode"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="分类名称" prop="cateName">
                <el-input v-model="editForm.cateName"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click.native="dialogFormVisible=false">取消</el-button>
          <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">添加</el-button>
          <el-button v-else type="primary" @click="editData">修改</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { _debounce } from '@/public/debounce.js';
export default {
  name: 'assetsType',
  props: {
    // 按钮级权限
    btns: {
      type: Object
    }
  },
  inject: ['reload'],
  watch: {
    // 按钮权限数据
    btns (val, oldVal) {
      // 刷新当前页
      this.reload();
    }
  },
  data () {
    return {
      // 所有公司数据
      compList: [],

      // 模糊搜索
      restaurants: [],
      timeout: null,

      // 资产数据
      assetsList: [],

      // 父级数据
      parentList: [],

      // 按钮显示隐藏  - 默认值
      btnSel: true,
      btnDel: true,
      btnUpload: true,
      btnDown: true,
      btnAdd: true,
      btnEdit: true,

      // 搜索条件
      formInline: {
        cateName: ''
      },

      // 列表数据
      assetsTypeData: [{}],
      // 当前页
      currentPage: 1,
      // 当前数
      pageSize: 20,
      // 总条目数
      total: 20,

      isedit: true,
      // 弹窗类别
      dialogStatus: '',
      // 弹窗标题
      textMap: {
        edit: '修改信息',
        create: '添加信息'
      },
      // 弹窗是否显示
      dialogFormVisible: false,

      // 列表选中列
      sels: [],

      // 编辑界面输入框校验规则
      editFormRules: {
        compId: [{ required: true, message: '请选择所属公司', trigger: 'change' }],
        parentId: [{ required: true, message: '请选择归属类目', trigger: 'change' }],
        cateCode: [{ required: true, message: '请输入分类编号', trigger: 'blur' }],
        cateName: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
      },

      // 界面默认数据
      editForm: {
        compId: '',
        parentId: '',
        cateCode: '',
        cateName: ''
      }
    };
  },

  // 实例创建后执行
  created () {
    // 按钮级授权
    this.authorization(this.$store.state.btns);

    // 加载分页数据
    this.getAssetsTypeDataByPage();

    // 获取所有公司
    this.getcompList();

    // 获取所有资产数据
    this.getAssets();

    // 获取父级列表
    this.getParent();
  },

  // 过滤器
  filters: {

    // 父级名称过滤
    getName (value, params) {
      if (params.length > 0) {
        for (let i = params.length; i--;) {
          if (value === 0) {
            return '无';
          }
          if (params[i].id === value) {
            return params[i].cateName;
          }
        }
      }
    }
  },

  mounted () {
    this.restaurants = this.loadAll();
  },

  methods: {

    // 按钮级授权
    authorization (data) {
      let _this = this;
      for (let i in data) {
        if (data['sel'] === 0) {
          _this.btnSel = false;
        }
        if (data['add'] === 0) {
          _this.btnAdd = false;
        }
        if (data['del'] === 0) {
          _this.btnDel = false;
        }
        if (data['upload'] === 0) {
          _this.btnUpload = false;
        }
        if (data['down'] === 0) {
          _this.btnDown = false;
        }
        if (data['edit'] === 0) {
          _this.btnEdit = false;
        }
        return i;
      }
    },

    // 获取所有公司
    getcompList () {
      let _this = this;
      // 获取所有公司数据
      _this.$http.get('api/findAllCompNoPage').then(res => {
        let { code, datas } = res;
        if (code === 0) {
          this.compList = datas;
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 获取所有资产数据
    getAssets () {
      let _this = this;
      _this.$http.post('api/findAllCate').then(res => {
        let { code, datas } = res;
        // 判断Code状态
        if (code === 0) {
          // 所有资产信息赋值
          datas.map(key => {
            _this.assetsList.push({
              value: key.cateName
            });
          });
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 模糊搜索
    loadAll () {
      return this.assetsList;
    },

    // 自动检索匹配
    querySearchAsync (queryString, cb) {
      let _this = this;
      let restaurants = _this.restaurants;
      let results = queryString ? restaurants.filter(_this.createStateFilter(queryString)) : restaurants;

      clearTimeout(_this.timeout);
      _this.timeout = setTimeout(() => {
        cb(results);
      }, 300 * Math.random());
    },

    // 查询
    createStateFilter (queryString) {
      return (state) => {
        return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },

    // 选中赋值
    handleSelect (item) {
      this.formInline.cateName = item.value;
    },

    // 获取所有父级
    getParent () {
      let _this = this;
      let params = {
        parentId: 0
      };
      // 获取所有角色
      _this.$http.post('api/findCateByParentId', params).then(res => {
        let { code, datas } = res;
        // 判断Code状态
        if (code === 0) {
          // 所有角色信息赋值
          _this.parentList = datas;
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 显示编辑界面
    editHandle: function (row) {
      let _this = this;
      // 弹窗类型
      _this.dialogStatus = 'edit';
      // 弹窗显示状态
      _this.dialogFormVisible = true;

      // 弹窗表单初始化显示数据
      _this.editForm = Object.assign({}, row);
      if (row.parentId === 0) {
        _this.editForm.parentId = row.parentId.toString();
      } else {
        _this.editForm.parentId = row.parentId;
      }
    },

    // 显示新增界面
    addHandle: function () {
      let _this = this;
      // 是否允许修改
      _this.isedit = false;
      // 弹窗类型
      _this.dialogStatus = 'create';
      // 弹窗显示状态
      _this.dialogFormVisible = true;
      // 重置新增界面默认数据
      _this.editForm = {
        compId: '',
        parentId: '',
        cateCode: '',
        cateName: ''
      };
    },

    // 查询
    selHandle: function () {
      let _this = this;
      // 收集请求数据
      let params = {
        cateName: _this.formInline.cateName === null ? '' : _this.formInline.cateName,
        pageNum: _this.currentPage,
        pageSize: _this.pageSize
      };

      // 根据角色ID获取分页数据
      _this.$http.raw('api/findAssetCateList', params).then(res => {
        let { code, datas } = res;
        if (code === 0) {
          // 总页数
          _this.total = datas.total;
          // 数据结果集
          _this.assetsTypeData = datas.list;
          // 解决删除当前页数据后仍留在那一页 不跳回上一页的bug
          if (!datas.list.length && _this.currentPage !== 1) {
            // 当前页减一
            _this.currentPage -= 1;
            // 调用自己
            _this.getAssetsTypeDataByPage();
          }
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 修改
    editData: _debounce(function () {
      let _this = this;
      _this.$nextTick(() => {
      // 判断是否通过验证规则验证
        _this.$refs['editForm'].validate(valid => {
          if (valid) {
            // 收集请求数据
            let params = {
              id: _this.editForm.id,
              parentId: _this.editForm.parentId === null ? '' : _this.editForm.parentId,
              compId: _this.editForm.compId === null ? '' : _this.editForm.compId,
              cateCode: _this.editForm.cateCode === null ? '' : _this.editForm.cateCode,
              cateName: _this.editForm.cateName === null ? '' : _this.editForm.cateName
            };
            // 修改类目信息
            _this.$http.raw('api/updateAssetCate', params).then(res => {
              let { code } = res;
              // 判断Code状态
              if (code === 0) {
                _this.$message({
                  message: '修改成功！',
                  type: 'success'
                });
                _this.$refs['editForm'].resetFields();
                _this.dialogFormVisible = false;
                // 刷新列表
                _this.getAssetsTypeDataByPage();
                _this.getAssets();
              }
            }).catch(err => {
              if (err === undefined) {
                _this.$message({
                  message: '服务器响应异常！',
                  type: 'error'
                });
                return false;
              }
            });
          }
        });
      });
    }, 200),

    // 添加
    createData: _debounce(function () {
      let _this = this;
      _this.$nextTick(() => {
        // 判断是否通过验证规则验证
        _this.$refs['editForm'].validate(valid => {
          if (valid) {
            // 收集请求数据
            let params = {
              parentId: _this.editForm.parentId === null ? '' : _this.editForm.parentId,
              compId: _this.editForm.compId === null ? '' : _this.editForm.compId,
              cateCode: _this.editForm.cateCode === null ? '' : _this.editForm.cateCode,
              cateName: _this.editForm.cateName === null ? '' : _this.editForm.cateName
            };
            // 添加类目信息
            _this.$http.raw('api/insertAssetCate', params).then(res => {
              let { code } = res;
              // 判断Code状态
              if (code === 0) {
                _this.$message({
                  message: '添加成功！',
                  type: 'success'
                });
                _this.$refs['editForm'].resetFields();
                _this.dialogFormVisible = false;
                // 刷新列表
                _this.getAssetsTypeDataByPage();
                _this.getAssets();
              }
            }).catch(err => {
              if (err === undefined) {
                this.$message({
                  message: '服务器响应异常！',
                  type: 'error'
                });
                return false;
              }
            });
          }
        });
      });
    }, 200),

    // 删除
    handleDelete (data) {
      let _this = this;
      // 删除二次确认
      _this.$confirm('确认删除选中的信息吗？', '提示', {
        type: 'warning'
      }).then(() => {
        let params = [data.id];
        _this.$http.raw('api/batchDelCate', params).then(res => {
          let { code } = res;
          if (code === 0) {
            _this.$message({
              type: 'success',
              message: '删除成功！'
            });
            // 刷新列表
            _this.getAssetsTypeDataByPage();
            _this.getAssets();
          }
        }).catch(err => {
          if (err === undefined) {
            _this.$message({
              message: '服务器响应异常！',
              type: 'error'
            });
            return false;
          }
        });
      }).catch(() => {
        _this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    // 全选、单选、多选
    selsChange: function (sels) {
      this.sels = sels;
    },

    // 批量删除
    batchRemove: function () {
      let _this = this;
      // 判断是否选择数据
      if (!_this.sels.length) {
        _this.$message.warning('您还没选择任何数据！');
        return;
      }
      // 删除二次确认
      _this.$confirm('确认删除选中的信息吗？', '提示', {
        type: 'warning'
      }).then(() => {
        let params = [];
        // 获取所有勾选ID
        _this.sels.map(item => {
          return params.push(item.id);
        });
        // 批量删除
        _this.$http.raw('api/batchDelCate', params).then(res => {
          let { code } = res;
          // 判断Code状态
          if (code === 0) {
            _this.$message({
              type: 'success',
              message: '批量删除成功！'
            });
            // 刷新列表
            _this.getAssetsTypeDataByPage();
            _this.getAssets();
          }
        }).catch(err => {
          if (err === undefined) {
            _this.$message({
              message: '服务器响应异常！',
              type: 'error'
            });
            return false;
          }
        });
      }).catch(() => {
        _this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    // 刷新页面数据
    getAssetsTypeDataByPage () {
      let _this = this;
      // 收集请求信息
      let params = {
        cateName: _this.formInline.cateName === null ? '' : _this.formInline.cateName,
        pageNum: _this.currentPage,
        pageSize: _this.pageSize
      };
      // 获取分页数据
      _this.$http.raw('api/findAssetCateList', params).then(res => {
        let { code, datas } = res;
        if (code === 0) {
          _this.total = datas.total;
          _this.assetsTypeData = datas.list;
          // 解决删除当前页数据后仍留在那一页 不跳回上一页的bug
          if (!datas.list.length && _this.currentPage !== 1) {
            // 当前页减一
            _this.currentPage -= 1;
            // 调用自己
            _this.getAssetsTypeDataByPage();
          }
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 每页显示的条数改变
    handleSizeChange (val) {
      this.pageSize = val;
      // 调用刷新页面
      this.getAssetsTypeDataByPage();
    },
    // 当前页码
    handleCurrentChange (val) {
      this.currentPage = val;
      // 调用
      this.getAssetsTypeDataByPage();
    }
  }
};
</script>

<style lang='scss' scoped>
@import './index.scss';
</style>
